package com.hao.epidemic_prevention.security.config;

import com.hao.epidemic_prevention.security.adminlogin.AdminServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class MyAuthenticationProvider implements AuthenticationProvider {

    // ~ Instance Fields
    // -----------------------------------------------------------------------------------------------------------------

    @Autowired
    private AdminServiceImpl adminServiceImpl;

    @Autowired
    private PasswordEncoder passwordEncoder;

    private Logger logger = LoggerFactory.getLogger(getClass());
    //private static MyPasswordEncoder myPasswordEncoder = new MyPasswordEncoder();

    // ~ Override Methods
    // -----------------------------------------------------------------------------------------------------------------

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 获取用户输入的用户名和密码
        final String username = authentication.getName();
        final String password = authentication.getCredentials().toString();
        // 获取封装用户信息的对象
        UserDetails userDetails = adminServiceImpl.loadUserByUsername(username);
        // 进行密码的比对
        logger.info("Provider-密码验证: " + userDetails.getPassword() + " " + passwordEncoder.encode(password));
        boolean flag = passwordEncoder.matches(password, userDetails.getPassword());

        // 校验通过
        if (flag) {
            logger.info("Provider-登录成功" + userDetails.getAuthorities());
            // 将权限信息也封装进去
            return new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
        }
        else {
            logger.info("Provider-登录失败");
            throw new AuthenticationException("用户或密码错误") {};
        }

    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }


    /*public void setMyPasswordEncoder(MyPasswordEncoder myPasswordEncoder) {
        this.myPasswordEncoder = myPasswordEncoder;
    }*/
    // ~ Autowired
    // -----------------------------------------------------------------------------------------------------------------

    /*@Autowired
    public void setUserDetailsServiceImpl(AdminServiceImpl adminServiceImpl) {
        this.adminServiceImpl = adminServiceImpl;
    }*/
}